//
//  DSNewBander.swift
//  Competition
//
//  Created by 段帅 on 16/6/20.
//  Copyright © 2016年 newfuture. All rights reserved.
//

import UIKit

@objc  protocol DSBanderDelegate {
    
    func clickImage(data:BannerModel) 
    
}



class DSNewBander: UIView,UIScrollViewDelegate {

    
    var timer:NSTimer!
    var scroll:UIScrollView!
    var adImageView:UIImageView!
    var pageControl:UIPageControl!
    var leftImage:UIImageView!
    var midImage:UIImageView!
    var rightImage:UIImageView!
    var imageArr = [UIImage]() //要展示的图片数组
    var current = 0  //当前页数
    var dataAD = [BannerModel]()
    var delegation : DSBanderDelegate!

      func loadData(data:NSArray){
        
        stopTimer()
        dataAD = data as! [BannerModel]
        if data.count == 1 {
            
            pageControl?.removeFromSuperview()
            scroll?.removeFromSuperview()
            adImageView = UIImageView()
            adImageView.frame = bounds;
            
            let model = data[0] as! BannerModel
            
           adImageView.sd_setImageWithURL(NSURL(string: model.imageurl), placeholderImage: nil, options: .ProgressiveDownload)
            current = 0
            let tap = UITapGestureRecognizer(target: self, action: "clickTap:")
            adImageView.addGestureRecognizer(tap)
            adImageView.userInteractionEnabled = true
            
            
            
            addSubview(adImageView)
            
        }else{
            /*
            1 创建scroll 设置为3*
            
            2 将第一张图片加载到中间   左边加载最后一张   右边加载第二章
            3启动定时器   滚到右边图片
            4刷新中间图片   滚回中间 
            5 刷新两边的图片
            
            
            
            */
           
            createImageArr(data)
            
            
            adImageView?.removeFromSuperview()
            
            scroll = UIScrollView()
            scroll.frame = CGRectMake(0, 0, SIZEWIDTH, frame.size.height)
            scroll.delegate = self
            scroll.pagingEnabled = true
            
            scroll.contentSize = CGSizeMake(SIZEWIDTH*3, 0)
            addSubview(scroll)
           leftImage = UIImageView.init(frame: CGRectMake(0, 0, SIZEWIDTH, frame.size.height))
           scroll.addSubview(leftImage)
            midImage = UIImageView.init(frame: CGRectMake(SIZEWIDTH, 0, SIZEWIDTH, frame.size.height))
            scroll.addSubview(midImage)
            rightImage = UIImageView.init(frame: CGRectMake(SIZEWIDTH*2, 0, SIZEWIDTH, frame.size.height))
            scroll.addSubview(rightImage)
            
            midImage.image = imageArr[current] 
            leftImage.image = imageArr.last
            rightImage.image = imageArr[1] 
            scroll.contentOffset = CGPointMake(SIZEWIDTH, 0)
            
            //启动定时器
            startTimer()
            
            //添加页数器
            pageControl = UIPageControl()
           pageControl.center = CGPointMake(SIZEWIDTH/2, frame.size.height-20)
            
            pageControl.numberOfPages = imageArr.count
            pageControl.currentPage = 0
            pageControl.backgroundColor = UIColor.redColor()
            
            addSubview(pageControl)
            
            //给中间视图添加手势
            let tap = UITapGestureRecognizer(target: self, action: "clickTap:")
            midImage.addGestureRecognizer(tap)
            
            midImage.userInteractionEnabled = true
            
            
            
            
        }
        
        
        
        
    }
    
    func clickTap(tap:UITapGestureRecognizer){
        
       let dic = dataAD[current] 
        
        delegation.clickImage(dic)
        
        
    }
   
    
    //创建图片数组
    func createImageArr(data:NSArray){
        
        imageArr = [UIImage]()
        
        for  model in dataAD {
            let image = UIImage(data: NSData(contentsOfURL:NSURL(string:model.imageurl)!)!)
            
            imageArr += [image!]
            
            
        }
        
        
        
        
    }
    
    
    func startTimer(){
        timer = NSTimer.init(timeInterval: 2, target: self, selector: "roll", userInfo: nil, repeats: true)
        
        NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
        
        
        
    }
    func stopTimer(){
        timer?.invalidate()
        timer = nil
        
        
        
        
    }
    
    func roll(){
        print("11111111")
        
        scroll.setContentOffset(CGPointMake(SIZEWIDTH*2, 0), animated: true)
        current++
        if current > imageArr.count-1 {
            
            current = 0
            
            
        }
        
        pageControl.currentPage = current
        
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
    let point = scrollView.contentOffset
        if(point.x/SIZEWIDTH == 2) {
            
            midImage.image = imageArr[current] 
            
            scrollView.setContentOffset(CGPointMake(SIZEWIDTH, 0), animated: false)
//            scroll.contentOffset = CGPointMake(SIZEWIDTH, 0)
            
            leftImage.image = imageArr[current-1<0 ? imageArr.count-1 : current-1] 
            rightImage.image = imageArr[current+1 > imageArr.count-1 ? 0 : current+1] 
            
            
            
        }
        
        
        
    }
    
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        let point = scrollView.contentOffset
        if point.x/SIZEWIDTH == 2 {
            
            current++
            if current > imageArr.count-1 {
                
                current = 0
                
                
            }
            
            midImage.image = imageArr[current] 
            
            scrollView.setContentOffset(CGPointMake(SIZEWIDTH, 0), animated: false)
            //            scroll.contentOffset = CGPointMake(SIZEWIDTH, 0)
            
            leftImage.image = imageArr[current-1<0 ? imageArr.count-1 : current-1] 
            rightImage.image = imageArr[current+1 > imageArr.count-1 ? 0 : current+1] 
            
          
            
            
            
        }
        
        if point.x == 0 {
            current--
            if current < 0 {
                
                
                current = imageArr.count-1
                
            }
            
            midImage.image = imageArr[current] 
            
            scrollView.setContentOffset(CGPointMake(SIZEWIDTH, 0), animated: false)
            //            scroll.contentOffset = CGPointMake(SIZEWIDTH, 0)
            
            leftImage.image = imageArr[current-1<0 ? imageArr.count-1 : current-1] 
            rightImage.image = imageArr[current+1 > imageArr.count-1 ? 0 : current+1] 
            
            
            
        }
          pageControl.currentPage = current
        
        
        startTimer()

    }
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
           }
    func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        stopTimer()
    }
    

    
    
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */

}
